
from flask import Flask, request, render_template, Response, g, jsonify
from camera import VideoCamera
import sqlite3
from datetime import datetime
import base64
from PIL import Image
from io import BytesIO
import numpy as np
import time
from face_recog.deploy import face_recog
import cv2

def base64_to_img(ori_img):
    """
        将base64位数据转为cv2读取得到的图片
    :param ori_img:
    :return:
    """

    base64Image = ori_img.replace("%2B", "+").replace("%3D", "=").replace("%2F", "/")
    img = base64.b64decode(base64Image)
    img_array = np.frombuffer(img, np.uint8)
    ori_img = cv2.imdecode(img_array, cv2.COLOR_RGB2BGR)

    if len(ori_img.shape) == 2:
        #单通道转三通道
        ori_img = cv2.cvtColor(ori_img, cv2.COLOR_GRAY2BGR)
    elif len(ori_img.shape) == 3:
        h_, w_, c_ = ori_img.shape
        if c_ == 4:
            ori_img = ori_img[:, :, 0:3]

    return ori_img

app = Flask(__name__)

DATABASE = 'faces_db/faces.sqlite'

def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = sqlite3.connect(DATABASE)
    return db

@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()

def query_db(query, args=(), one=False):
    cur = get_db().execute(query, args)
    rv = cur.fetchall()
    cur.close()
    return (rv[0] if rv else None) if one else rv


@app.route('/')
def index():
    return 'service is runing.'

@app.route('/video')
def video_page():
    return render_template('index.html')


def gen(camera):
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')


@app.route('/video_feed')
def video_feed():
    return Response(gen(VideoCamera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')


@app.route('/userinfo', methods=['GET'])
def user_info():
    """根据用户id查询用户信息
    数据库中存储的是binary图片
    Returns:
        [type]: [description]
    """
    user_id = request.args.get('user_id')
    # print(user_id)
    sql_s = "select name, gender, department,image from user_info where user_id={user_id};".format(user_id=user_id)
    print('sql_s', sql_s)
    user_info = query_db(sql_s)
    # print(user_info)
    # image = Image.open()
    if user_info :
        return jsonify({'code':0,
                        'data':{
                            'name':user_info[0][0],
                            'gender':user_info[0][1],
                            'department':user_info[0][2],
                            'image':user_info[0][3], }
                        })
    else:
        return jsonify({"code":-1,
                    "msg": '不存在该用户'})


@app.route('/checkin', methods=['POST'])
def checkin():
    user_id = request.form.get('user_id')
    print(user_id)
    date_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    if user_id:
        insert_sql = "insert into clockin_log (user_id, date_time) values ({},'{}');".format(user_id, date_time)
    else:
        insert_sql = "insert into clockin_log (date_time) values ('{}');".format(date_time)
    print(insert_sql)
    try:
        db = get_db()
        db.execute(insert_sql)
        db.commit()
        db.close()
        return jsonify({
            'code': 0,
            'msg': 'sucess'
        })
    except Exception as e:
        return jsonify({
            'code': -1,
            'msg':'插入数据库出错'
        })


@app.route('/stats')
def stats():
    # 查询
    query_sql = """select 'yes' as staff, count(DISTINCT user_id) as num from clockin_log where user_id not null and date(date_time)=date ('now')
        union
        select 'no' as staff, count(*) as num from clockin_log where user_id is null and date(date_time)=date ('now');
    """
    staff_count = query_db(query_sql)
    if staff_count:
        return jsonify({
            'code': 0,
            'data':{
                'staff_yes': staff_count[1][1],
                'staff_no': staff_count[0][1]
            }
        })
    else:
        return jsonify({
            'code': -1,
            'msg': '查询出错'
        })


@app.route('/face_recog', methods=['POST'])
def face_recog_name():
    '''
    TODO
    输入单帧图片，返回识别出来的人脸信息，包括用户id，用户姓名，边框
    '''
    t_req = time.time()
    data = request.files['file']
    print(type(data))
    # img = np.array(Image.open(BytesIO(base64.b64decode(data))))
    img = base64_to_img(data)
    print('request___',(time.time()-t_req))

    if img is None:
        return jsonify({
            'code': -1,
        })
    t_rec =time.time()
    faces = face_recog.face_recog(img)
    print('recnigtion_____',(time.time()-t_rec))
    return jsonify({
        'code': 0,
        'data': faces
    })



if __name__ == '__main__':
    app.run(host='0.0.0.0',port=17103, debug=True)
